using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Text;
using A = Acrobat;

namespace Dimok {
	public class Acrobat {
		public static A.CAcroRect CreateRectInstance() {
			return (A.CAcroRect)Activator.CreateInstance(Type.GetTypeFromProgID("AcroExch.Rect", true), true);
		}
		public static AFORMAUTLib.AFormApp CreateAFormAppInstance() {
			Type oAForm = Type.GetTypeFromProgID("AFormAut.App", true);
			return (AFORMAUTLib.AFormApp)Activator.CreateInstance(oAForm, true);
		}
		public static A.CAcroPDDoc CreatePDDocInstance(string fileName) {
			A.CAcroPDDoc pdDoc = (A.CAcroPDDoc)Activator.CreateInstance(Type.GetTypeFromProgID("AcroExch.PDDoc", true), true);
			FileManager.WaitToLoad(fileName, 15 * 1000);
			pdDoc.Open(fileName);
			return pdDoc;
		}
		public static A.CAcroAVDoc CreateAVDocInstance() { return CreateAVDocInstance(""); }
		public static A.CAcroAVDoc CreateAVDocInstance(string fileName) {
			A.CAcroAVDoc avDoc = (A.CAcroAVDoc)Activator.CreateInstance(Type.GetTypeFromProgID("AcroExch.AVDoc", true), true);
			try {
				if (fileName != "") {
					FileManager.WaitToLoad(fileName, 15 * 1000);
					StreamReader sr = File.OpenText(fileName);
					try {
						if (sr.BaseStream.Length == 0)
							throw new System.IO.FileLoadException("Acrobat can't load empty file [" + fileName + "].");
					} finally {
						sr.Close();
					}
					Thread.Sleep(300);
					int res = avDoc.Open(fileName, "");
					if (avDoc.IsValid() != -1)
						throw new System.IO.FileLoadException("Acrobat can't load file " + fileName);
				}
			} catch (Exception exc) {
				try { avDoc.Close(1); } catch { }
				throw exc;
			}
			return avDoc;
		}
		public static void Dispose(params object[] refs) {
			foreach (object o in refs)
				while (o != null && Marshal.ReleaseComObject(o) > 0) { };
		}
		private static int CalcEndPage(ref int pageStart, int count) {
			pageStart = Math.Max(pageStart, 1);
			return count <= 0 ? -1 : pageStart + count - 1;
		}

	}
}
